package com.chen.jwt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.jwt.annotation.PassToken;
import com.chen.jwt.annotation.UserLoginToken;
import com.chen.jwt.config.Result;
import com.chen.jwt.config.ResultCode;
import com.chen.jwt.enumToken.Token;
import com.chen.jwt.mapper.UsersMapper;
import com.chen.jwt.pojo.Users;
import com.chen.jwt.utils.HttpServletRequestToken;
import com.chen.jwt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@SuppressWarnings("all")
@RequestMapping("api")
public class JwtController {
    @Resource
    private UsersMapper mapper;
    @Resource
    private HttpServletRequestToken httpServletRequestToken;
    @Resource
    private HttpServletRequest httpRequest;

    @Resource
    private RedisTemplate redisTemplate;

    // 认证

    @PassToken
    @PostMapping("/user/login")
//    @Async("asyncThreadPoolTaskExecutor")
    public Result login(@RequestBody Users user) {
        System.out.println("前端传来的用户数据：" + user);
        try {
            // 查询数据库
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            HashMap<String, Object> queryMap = new HashMap<>();
            queryMap.put("username", user.getUsername());
            queryMap.put("password", user.getPassword());
            queryWrapper.allEq(queryMap);
            Users userDb = mapper.selectOne(queryWrapper);
            // 认证失败
            if (userDb == null) {
                return new Result(ResultCode.USER_LONGIN_EXIST,"");
            }
            // 认证成功
            Map<String, String> tokenClaimsMap = new HashMap<>(); //用来存放payload
            tokenClaimsMap.put("id", userDb.getId());
            tokenClaimsMap.put("username", userDb.getUsername());
            String token = JWTUtils.getToken(tokenClaimsMap);
            // 返回的数据
            String replaceToken = token.toString();
            System.out.println(replaceToken);
            redisTemplate.opsForValue().set(Token.TOKEN,replaceToken,60, TimeUnit.SECONDS);
            return new Result(ResultCode.SUCCESS, token);
        } catch (Exception e) {
            // 认证失败，返回的数据
            e.printStackTrace();
            return new Result(ResultCode.ERROR, e);
        }
    }

    @UserLoginToken
    @GetMapping("/private/info")
    public String info(HttpServletRequest request) {
        String token = request.getHeader(Token.TOKEN);
        DecodedJWT tokenJWT = JWTUtils.getToken(token);
        System.out.println(tokenJWT.getClaim("username").asString());
        System.out.println(tokenJWT.getClaim("userId").asInt());
        return "这是一段私人信息。只有登录才能显示";
    }


    @UserLoginToken
    @GetMapping("private/Test")
    public Result info() {
        String code = "这是一段私人信息。只有登录才能显示";
        return new Result(ResultCode.SUCCESS, code);
    }

    @PassToken
    @GetMapping("private/Test2")
    public Result info2() throws Throwable {
        Users user = httpServletRequestToken.getUser(httpRequest);
        String code = "这是一段普通信息。不登录也能显示";
        return new Result(ResultCode.SUCCESS, user);
    }


}
